package com.denlaku.longan.service.impl;

import com.denlaku.longan.anno.RequiredTx;
import com.denlaku.longan.repository.LinkageRepository;
import com.denlaku.longan.service.LinkageAimService;
import com.denlaku.longan.service.LinkageService;
import com.denlaku.longan.util.SnowflakeUtils;
import com.denlaku.longan.vo.Linkage;
import com.denlaku.longan.vo.LinkageAim;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tianx
 */
@Service
public class LinkageServiceImpl implements LinkageService {
    @Autowired
    private LinkageRepository linkageRepository;

    @Autowired
    private LinkageAimService linkageAimService;

    @Override
    @RequiredTx
    public void batchAdd(List<Linkage> linkageList) {
        if (CollectionUtils.isEmpty(linkageList)) {
            return;
        }
        List<LinkageAim> aims = new ArrayList<>();
        for (Linkage linkage : linkageList) {
            linkage.setId(SnowflakeUtils.nextId());
            for (LinkageAim linkageAim : ListUtils.emptyIfNull(linkage.getAims())) {
                linkageAim.setComponentId(linkage.getComponentId());
                linkageAim.setLinkageId(linkage.getId());
                linkageAim.setId(SnowflakeUtils.nextId());
                aims.add(linkageAim);
            }
        }
        linkageAimService.batchAdd(aims);
        linkageRepository.batchAdd(linkageList);
    }

    @Override
    @RequiredTx
    public void delete(Long tenantId, List<Long> componentIds) {
        linkageAimService.delete(tenantId, componentIds);
        linkageRepository.delete(tenantId, componentIds);
    }

    @Override
    public List<Linkage> list(Long tenantId, List<Long> componentIds) {
        List<Linkage> linkages = linkageRepository.list(tenantId, componentIds);
        if (CollectionUtils.isEmpty(linkages)) {
            return Collections.emptyList();
        }
        List<LinkageAim> aimList = linkageAimService.list(tenantId, componentIds);
        Map<Long, List<LinkageAim>> aimMap = new HashMap<>(linkages.size());
        for (LinkageAim linkageAim : aimList) {
            Long linkageId = linkageAim.getLinkageId();
            aimMap.computeIfAbsent(linkageId, key -> new ArrayList<>()).add(linkageAim);
        }
        for (Linkage linkage : linkages) {
            Long id = linkage.getId();
            linkage.setAims(aimMap.getOrDefault(id, Collections.emptyList()));
        }
        return linkages;
    }

}
